package com.uenpay.oem.ui.main.my;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.qyx.android.message.type.PacketType;
import com.socks.library.KLog;
import com.uenpay.im.IMApplication;
import com.uenpay.im.configuration.APIConfiguration;
import com.uenpay.im.ui.old.activity.mycollect.MyCollectListActivity;
import com.uenpay.im.ui.old.activity.red.RedActivity;
import com.uenpay.im.ui.old.activity.wallet.StatementActivity;
import com.uenpay.im.utilities.ShareUtil;
import com.uenpay.im.utilities.ToastUtil;
import com.uenpay.im.utilities.Toasts;
import com.uenpay.oem.MyApplication;
import com.uenpay.oem.R;
import com.uenpay.oem.common.ACacheConstant;
import com.uenpay.oem.common.AppConstant;
import com.uenpay.oem.common.RxBusEventConstant;
import com.uenpay.oem.data.bean.UserAuthInfo;
import com.uenpay.oem.ui.auth.AuthActivity;
import com.uenpay.oem.ui.bankcard.MyBankCardActivity;
import com.uenpay.oem.ui.settings.SettingsActivity;
import com.uenpay.oem.ui.user.info.UserInfoActivity;
import com.uenpay.oem.util.share.FileUtil;
import com.uenpay.oem.util.share.ShareUtils;
import com.uenpay.util.app.base.BaseFragment;
import com.uenpay.util.common.ACache;
import com.uenpay.util.common.PreferenceHelper;
import com.uenpay.util.imageloader.ImageLoader;
import com.uenpay.util.imageloader.ImageLoaderUtil;
import com.uenpay.util.rx.CommonEvent;
import com.uenpay.util.rx.RxBus;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import cn.sharesdk.framework.ShareSDK;
import rx.Observable;
import rx.functions.Action1;

/**
 * Class Explain: 我的
 *
 * @author SL
 * @copyRight http://www.qiyunxin.com
 */

public class MyFragment extends BaseFragment implements MyContract.View {

	public static final String TAG = "MyFragment";

	@BindView(R.id.back_layout)
	LinearLayout backLayout;
	@BindView(R.id.conn_status)
	TextView connStatus;
	@BindView(R.id.title_textview)
	TextView titleTextview;
	@BindView(R.id.title_right_tv)
	TextView titleRightTv;
	@BindView(R.id.title_right_layout)
	RelativeLayout titleRightLayout;
	@BindView(R.id.title_right_contacts_iv)
	ImageView titleRightContactsIv;
	@BindView(R.id.title_right_add_iv)
	ImageView titleRightAddIv;
	@BindView(R.id.title_right_iv_layout)
	LinearLayout titleRightIvLayout;
	@BindView(R.id.title_layout)
	RelativeLayout titleLayout;
	@BindView(R.id.iv_avatar)
	ImageView myAvatar;
	@BindView(R.id.name_layout)
	LinearLayout nameLayout;
	@BindView(R.id.my_goahead)
	ImageView myGoahead;
	@BindView(R.id.my_name)
	TextView myName;
	@BindView(R.id.my_signature)
	TextView mySignature;
	@BindView(R.id.me_layout)
	RelativeLayout meLayout;
	@BindView(R.id.bank_iv)
	ImageView bankIv;
	@BindView(R.id.my_bank_card)
	ImageView myBankCard;
	@BindView(R.id.my_bank_layout)
	RelativeLayout myBankLayout;
	@BindView(R.id.wallet_iv)
	ImageView walletIv;
	@BindView(R.id.waller_goahead_iv)
	ImageView wallerGoaheadIv;
	@BindView(R.id.my_wallet_layout)
	RelativeLayout myWalletLayout;
	@BindView(R.id.red_iv)
	ImageView redIv;
	@BindView(R.id.my_red_layout)
	RelativeLayout myRedLayout;
	@BindView(R.id.collect_iv)
	ImageView collectIv;
	@BindView(R.id.my_collect_layout)
	RelativeLayout myCollectLayout;
	@BindView(R.id.about_iv)
	ImageView aboutIv;
	@BindView(R.id.my_about_layout)
	RelativeLayout myAbout;
	@BindView(R.id.base_iv)
	ImageView base_iv;
	@BindView(R.id.tv_user_name)
	TextView tvUserName;
	@BindView(R.id.tv_user_phone)
	TextView tvUserPhone;
	@BindView(R.id.iv_real_name_status)
	ImageView ivRealNameStatus;
	@BindView(R.id.bill_iv)
	ImageView billIv;
	@BindView(R.id.my_bill_card)
	ImageView myBillCard;
	@BindView(R.id.my_bill_layout)
	RelativeLayout myBillLayout;
	@BindView(R.id.tv_bankcard_count)
	TextView tvBankCardCount;
	@BindView(R.id.tv_money)
	TextView tvmoney;
	private boolean canSeebalance = true;
	private Unbinder mUnbinder;

	private UserAuthInfo mUserAuthInfo = null;
	private String mBalance;

	private MyContract.Presenter mPresenter;
	private String myFragment = "myFragment";
	private ACache cache;


	@Override
	protected void onCreateView(Bundle savedInstanceState) {
		super.onCreateView(savedInstanceState);
		setContentView(R.layout.fragment_my_layout);
		mUnbinder = ButterKnife.bind(this, getContentView());
		cache = ACache.get(getActivity());

		initView();
		initData();
	}

	@Override
	public void showUserInfo(UserAuthInfo info) {
		mUserAuthInfo = info;
		if (info.getIsReal() == UserAuthInfo.AUTH_TRUE) {
			ivRealNameStatus.setImageResource(R.drawable.ic_real_name);
		} else {
			ivRealNameStatus.setImageResource(R.drawable.ic_no_real_name);
		}
		if (info.getNumBC() > 0) {
			tvBankCardCount.setText("" + info.getNumBC());
		} else {
			tvBankCardCount.setText("前往添加银行卡");
		}

	}

	@Override
	public void showBalance(String balance) {
		mBalance = balance;
		if (TextUtils.isEmpty(balance)){
			tvmoney.setText("0.00元");
		}
		tvmoney.setText(balance+"元");
	}

	@Override
	public void showLoading() {

	}

	@Override
	public void dismissLoading() {

	}

	@Override
	public void setPresenter(Object presenter) {
		mPresenter = new MyPresenter(this);
	}

	@Override
	public void showToast(String msg) {

	}

	private void initData() {
		mPresenter.getUserInfo();
		mPresenter.getBalance();
		//初始化分享sdk
		initShare();
	}
	/**
	 * 初始化分享sdk,设置显示图标
	 */
	private void initShare() {
		ShareSDK.initSDK(getContext(), "173abd75c5265");
		Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
		String path = FileUtil.writeImageToSDCard(bmp);
		ShareUtils.setImagePath(path);
	}

	private void initView() {
		/*//先加载缓存的头像
		Bitmap asBitmap = cache.getAsBitmap(ACacheConstant.CACHE_AVATAR);
		if (null != asBitmap) {
			myAvatar.setImageBitmap(asBitmap);
		} else {
			myAvatar.setImageResource(R.drawable.default_avatar);
		}*/

		final String url = APIConfiguration.getAvatarUrlNormal(IMApplication.getCustId(), PacketType.PERSONAL);
		ImageLoaderUtil.getInstance().loadImage(getActivity(),
				new ImageLoader.Builder().isCache(false).roundRadius(6).url(url).imgView(myAvatar).build());
		tvUserName.setText(MyApplication.config.getUserName());
		String phone=MyApplication.getUserMobilePhone();
		String phone1=phone.substring(0,3);
		String phone2=phone.substring(phone.length()-4);
		tvUserPhone.setText(phone1+"****"+phone2);
		titleTextview.setText("我的");
		titleTextview.setTextColor(Color.BLACK);
		backLayout.setVisibility(View.GONE);
		titleLayout.setBackgroundColor(Color.WHITE);
		base_iv.setVisibility(View.VISIBLE);
		setPresenter(null);
		Observable<CommonEvent> observable = RxBus.$().register(TAG);
		RxBus.$().OnEvent(observable, new Action1<Object>() {
			@Override
			public void call(Object obj) {
				CommonEvent event = (CommonEvent) obj;
				KLog.d(TAG, "CommonEvent --->" + event.getWhat());
				if (event.getWhat() == RxBusEventConstant.EVENT_UPDATE_USER_AUTH_INFO) {
					mPresenter.getUserInfo();
					return;
				}
				if (event.getWhat() == RxBusEventConstant.EVENT_RECHARGE_SUCCESS) {
					mPresenter.getBalance();
					return;
				}
				if (event.getWhat() == RxBusEventConstant.EVENT_WITHDRAW_SUCCESS) {
					mPresenter.getBalance();
					return;
				}
				if(event.getWhat()==RxBusEventConstant.EVENT_NICK_NAME_CHANGED){
                    Object name = event.getObject();
                    MyApplication.config.setUserName(name.toString());
                    tvUserName.setText(name.toString());
					return;
                }
				if (event.getWhat() == RxBusEventConstant.EVENT_BANKCARD_CHANGE) {
					mPresenter.getUserInfo();
					return;
				}

				if(event.getWhat() == RxBusEventConstant.EVENT_AVATAR_CHANGE){
					ImageLoaderUtil.getInstance().loadImage(getActivity(),
							new ImageLoader.Builder().isCache(false).roundRadius(6).url(url).imgView(myAvatar).build());
				}
			}
		});
		canSeebalance = PreferenceHelper.readBoolean(getContext(), myFragment,
				AppConstant.CAN_SEE_BALANCE,true);


	}

	@OnClick(R.id.iv_real_name_status)
	public void checkAuth() {
		if (MyApplication.getUserAuthInfo() == null)
			return;
		if (MyApplication.getUserAuthInfo().getIsReal() == UserAuthInfo.AUTH_FALSE) {
			Intent authIt = new Intent(getActivity(), AuthActivity.class);
			startActivity(authIt);
		}
	}

	@OnClick(R.id.ll_eye_layout)
	public void balanceVisible(){
		canSeebalance = !canSeebalance;
		PreferenceHelper.write(getContext(),myFragment,AppConstant.CAN_SEE_BALANCE,canSeebalance);
		showBalance(mBalance);
	}



	@OnClick({ R.id.me_layout, R.id.my_bill_layout,R.id.my_bank_card, R.id.my_bank_layout,
			R.id.my_wallet_layout, R.id.my_red_layout, R.id.my_collect_layout, R.id.my_about_layout,
			R.id.base_iv ,R.id.rl_mybalance,R.id.rl_share_layout})
	public void onClick(View view) {
		switch (view.getId()) {
		// 详情页面
		case R.id.me_layout:
			Intent intent = new Intent();
			intent.setClass(getActivity(), UserInfoActivity.class);
			startActivity(intent);
			break;
		// 我的账单
		case R.id.my_bill_layout:
			Intent it = new Intent(getActivity(), StatementActivity.class);
			startActivity(it);
			break;

		case R.id.my_bank_card:
			break;
		case R.id.my_bank_layout:
			if (mUserAuthInfo == null) {
				ToastUtil.showToast(getActivity(), "未获取到用户信息");
				return;
			}
			Intent intent_bank = new Intent(getActivity(), MyBankCardActivity.class);
			startActivity(intent_bank);

                break;
            case R.id.my_wallet_layout:
                break;
            case R.id.my_red_layout:
                Intent intent_red = new Intent(getActivity(), RedActivity.class);
                startActivity(intent_red);
                break;
            case R.id.my_collect_layout:
                Intent intent_collect = new Intent(getActivity(), MyCollectListActivity.class);
                startActivity(intent_collect);
                break;
            case R.id.my_about_layout:
                break;
            // 点击设置跳转
            case R.id.base_iv:
                startActivity(new Intent(getActivity(), SettingsActivity.class));
                break;
            case R.id.rl_mybalance:
                if(null == mUserAuthInfo){
					ToastUtil.showToast(getActivity(), "未获取到用户信息");
                    return;
                }
                if(mUserAuthInfo.getNumBC()<1){
                    ToastUtil.showToast(getContext(),"请先添加银行卡");
                    return;
                }
                startActivity(new Intent(getActivity(), MyBalanceActivity.class));
                break;
			//点击分享
			case R.id.rl_share_layout:
				ShareUtils.setImagePath("");
				ShareUtils.showShare(getActivity());
				break;
        }
    }

	@Override
	public void onResume() {
		super.onResume();
		mPresenter.getBalance();
	}

	@Override
	public void onDestroyView() {
		super.onDestroyView();
		mUnbinder.unbind();
		ShareUtils.destroyShare();
		RxBus.$().unregister(this);
	}
}
